//
//  HJUserNotifications.m
//  KaiChat
//
//  Created by lx on 2024/1/21.
//

#import "HJUserNotifications.h"
//#import <Intents/Intents.h>
//#import <UserNotifications/UserNotifications.h>
#import <AVFoundation/AVFoundation.h>
#import <AudioToolbox/AudioToolbox.h>
#import "HJChatSessionModel.h"
#import "HJChatMessageModel.h"
#import "HJIM.h"
#import "HJChatController.h"

@class HJConversationController, HJChatController;

@interface HJNotificationModel : NSObject

@property (nonatomic, copy) NSString *title;
@property (nonatomic, copy) NSString *body;
@property (nonatomic, copy) NSString *avatarUrl;
@property (nonatomic, strong) UIImage *avatarImage;
@property (nonatomic, strong) UIImage *subAvatarImage;
@property (nonatomic, strong) NSNumber *filterKey;
@property (nonatomic, copy) NSString *sessionId;
@property (nonatomic, copy) NSString *msgId;
@property (nonatomic, copy) NSString *sendUserId;
@property (nonatomic, assign) HJChatType chatType;

@end

@implementation HJNotificationModel




@end


@interface HJNotificationView : UIView

@property (nonatomic, readonly) CGSize contentSize;
@property (nonatomic, strong) HJNotificationModel *model;

@end


@interface HJNotificationView ()

@property (nonatomic, weak) UIVisualEffectView *backgroundView;
@property (nonatomic, weak) UIView *contentView;
@property (nonatomic, weak) UIImageView *avatarImageView;
@property (nonatomic, weak) UIImageView *subAvatarImageView;
@property (nonatomic, weak) UILabel *titleLabel;
@property (nonatomic, weak) UILabel *bodyLabel;
@property (nonatomic, weak) UILabel *dateLabel;
@property (nonatomic, strong) dispatch_block_t delayedBlock;


@end


@implementation HJNotificationView


- (instancetype)initWithFrame:(CGRect)frame {
    if (self = [super initWithFrame:frame]) {
        
        self.clipsToBounds = YES;
        
        self.layer.shadowColor = UIColor.blackColor.CGColor;
        self.layer.shadowOffset = CGSizeZero;
        self.layer.shadowRadius = 20;
        self.layer.shadowOpacity = 0.1;
        self.layer.cornerRadius = 20;
        self.layer.masksToBounds = NO;
        
        UIBlurEffect *effect = [UIBlurEffect effectWithStyle:UIBlurEffectStyleLight];
        
        UIVisualEffectView *backgroundView = [[UIVisualEffectView alloc] initWithEffect:effect];
        backgroundView.backgroundColor = [UIColor.tj_grayColor colorWithAlphaComponent:0.5];
        [self addSubview:backgroundView];
        backgroundView.layer.cornerRadius = 20;
        backgroundView.layer.masksToBounds = YES;
        
        UIView *contentView = [[UIView alloc] init];
        [self addSubview:contentView];
        
        UIImageView *avatarImageView = [UIImageView addToView:contentView];
        avatarImageView.tj_size = CGSizeMake(36, 36);
        avatarImageView.addCornerRadius(18);
        
        UIImageView *subAvatarImageView = [UIImageView addToView:contentView];
        subAvatarImageView.tj_size = CGSizeMake(16, 16);
        subAvatarImageView.addCornerRadius(3);
        
        UILabel *titleLabel = [UILabel lableWithSuperView:contentView font:UIFontMediumMake(15) color:UIColor.blackColor title:nil textAlignment:NSTextAlignmentLeft];
        
        UILabel *bodyLabel = [UILabel lableWithSuperView:contentView font:UIFontMake(15) color:UIColor.tj_333333Color title:nil textAlignment:NSTextAlignmentLeft];
        bodyLabel.numberOfLines = 2;
        
        UILabel *dateLabel = [UILabel lableWithSuperView:contentView font:UIFontMake(14) color:UIColor.tj_666666Color title:nil textAlignment:NSTextAlignmentLeft];
        
        _contentView = contentView;
        _backgroundView = backgroundView;
        _avatarImageView = avatarImageView;
        _subAvatarImageView = subAvatarImageView;
        
        _titleLabel = titleLabel;
        _bodyLabel = bodyLabel;
        _dateLabel = dateLabel;
        
    }
    return self;
}

- (void)setModel:(HJNotificationModel *)model {
    _model = model;
    
    _titleLabel.text = model.title;
    _bodyLabel.text = model.body;
    _subAvatarImageView.image = model.subAvatarImage;
    if (model.avatarImage) {
        _avatarImageView.image = model.avatarImage;
    } else if (model.avatarUrl) {
        [_avatarImageView tj_setImageWithUrl:model.avatarUrl placeholderImage:[UIImage imageNamed:defaultAvatarName]];
    }
    
    
    CGFloat selfHeight = 64;
    CGFloat selfWidth = KScreenWidth - 20;
    CGFloat titleBodyMargin = 3;
    CGFloat topBottomMargin = 14;
    CGFloat leftMargin = 14;
    
    CGFloat avatarTitleMargin = 12;
    
    CGSize titleSize = [model.title getStringSizeWithWidth:selfWidth - avatarTitleMargin - leftMargin * 2 - _avatarImageView.tj_width font:_titleLabel.font];
    titleSize.height = _titleLabel.font.lineHeight;
    CGSize bodySize = [model.body getStringSizeWithWidth:selfWidth - avatarTitleMargin - leftMargin * 2 - _avatarImageView.tj_width font:_bodyLabel.font];
    
    if (bodySize.height > _bodyLabel.font.lineHeight * 2) {
        bodySize.height = _bodyLabel.font.lineHeight * 2;
    }
    
    selfHeight = topBottomMargin + titleSize.height + bodySize.height + titleBodyMargin + topBottomMargin;
    
    _avatarImageView.frame = CGRectMake(leftMargin, (selfHeight - _avatarImageView.tj_height) * 0.5, _avatarImageView.tj_width, _avatarImageView.tj_height);
    _titleLabel.frame = CGRectMake(_avatarImageView.tj_MaxX + avatarTitleMargin, topBottomMargin, titleSize.width, titleSize.height);
    _bodyLabel.frame = CGRectMake(_titleLabel.tj_x, _titleLabel.tj_MaxY + titleBodyMargin, bodySize.width, bodySize.height);
    self -> _contentSize = CGSizeMake(selfWidth, selfHeight);
    
    if (model.subAvatarImage) {
        _subAvatarImageView.frame = CGRectMake(_avatarImageView.tj_MaxX - _subAvatarImageView.tj_width + 3, _avatarImageView.tj_MaxY - _subAvatarImageView.tj_height + 3, _subAvatarImageView.tj_width, _subAvatarImageView.tj_height);
    } else {
        _subAvatarImageView.frame = CGRectZero;
    }
    
}

- (void)layoutSubviews {
    [super layoutSubviews];
    
    _backgroundView.frame = self.bounds;
    _contentView.frame = self.bounds;
}


@end


@interface HJUserNotifications()


@property (nonatomic, strong) NSMutableArray *notificationsQueue;
@property (nonatomic, strong) NSMutableDictionary *filterPool;
@property (nonatomic, assign) BOOL executing;
@property (nonatomic, strong) UIPanGestureRecognizer *panGestureRecognizer;
@property (nonatomic, assign) CGFloat panMaxY;
@property (nonatomic, assign) CGFloat panInitialY;
@property (nonatomic, strong) HJNotificationView *notificationsView;
@property (nonatomic, strong) HJUserModel *userSettingModel;


@end


@implementation HJUserNotifications

+ (HJUserNotifications *)shareNotifications {
    return [[HJUserNotifications alloc] init];
}

+ (instancetype)allocWithZone:(struct _NSZone *)zone {
    static dispatch_once_t onceToken;
    static HJUserNotifications *_userNotifications = nil;
    dispatch_once(&onceToken, ^{
        if (_userNotifications == nil) {
            _userNotifications = [super allocWithZone:zone];
        }
    });
    return _userNotifications;
}

- (NSMutableArray *)notificationsQueue {
    if (!_notificationsQueue) {
        _notificationsQueue = [NSMutableArray array];
    }
    return _notificationsQueue;
}

- (NSMutableDictionary *)filterPool {
    if (!_filterPool) {
        _filterPool = [NSMutableDictionary dictionary];
    }
    return _filterPool;
}

+ (void)pushNotificationsWithTitle:(nullable NSString *)title subtitle:(nullable NSString *)subtitle body:(nullable NSString *)body avatarImage:(nullable UIImage *)avatarImage msgId:(NSString *)msgId sessionId:(NSString *)sessionId sendUserId:(nullable NSString *)sendUserId {
    HJUserNotifications *userNotifications = [HJUserNotifications shareNotifications];
//    userNotifications.sendUserId = sendUserId;
//    userNotifications.msgId = msgId;
//    userNotifications.sessionId = sessionId;
    [userNotifications pushNotificationsWithTitle:title subtitle:subtitle body:body avatarImage:avatarImage appLogo:nil];
}


+ (void)pushNotificationsWithSessionModel:(HJChatSessionModel *)sessionModel messageModel:(HJChatMessageModel *)messageModel {
    
    UIViewController *viewController = HJTools.currentViewController;
    NSString *stringClasss = NSStringFromClass(viewController.class);
    if ([stringClasss isEqualToString:@"HJConversationController"] ||
        [stringClasss isEqualToString:@"HJGroupChatController"] ||
        [stringClasss isEqualToString:@"HJSingleChatController"]
        ) {
        return;
    }
    
    if (sessionModel.messageType == HJMessageTypeNotice) return;
    
    if (sessionModel.messageType == HJMessageTypeSystem || sessionModel.messageType == HJMessageTypeOtherSystem || sessionModel.chatType == HJChatTypeSystem) {
        if (messageModel.systemMsgType != HJChatSystemMsgTypeApplyFridend || messageModel.systemMsgType == HJChatSystemMsgTypeApplyFridendAgree) {
            return;
        }
    }
    
    dispatch_async_sql_queue(^{
        HJUserModel *userSettingModel = [HJUserModel currentAccountModel];
        if (!userSettingModel.noticeOpen) {
            return;
        }
        
        dispatch_async_main_queue(^{
            
            HJUserNotifications *userNotifications = [HJUserNotifications shareNotifications];
            userNotifications.userSettingModel = userSettingModel;

            HJNotificationModel *notificationModel = [[HJNotificationModel alloc] init];
            notificationModel.sendUserId = messageModel.senderId;
            notificationModel.msgId = messageModel.msgId;
            notificationModel.sessionId = messageModel.sessionId;
            notificationModel.title = sessionModel.sessionName;
            notificationModel.chatType = sessionModel.chatType;
            notificationModel.subAvatarImage = [UIImage imageNamed:@"notice_logo_icon"];
            
            NSString *senderName = messageModel.senderNickname;
            
            if (messageModel.chatType == HJChatTypeSingle) {
                notificationModel.body = [sessionModel getMessgetContent];
            } else {
                if (senderName && [messageModel getMessgetContent]) {
                    notificationModel.body = [NSString stringWithFormat:@"%@: %@", senderName, [sessionModel getMessgetContent]];
                } else {
                    notificationModel.body = [sessionModel getMessgetContent];
                }
            }
          
            if (sessionModel.chatType == HJChatTypeSingle) {
                notificationModel.avatarUrl = messageModel.senderAvatar;
            } else {
                notificationModel.avatarUrl = sessionModel.sessionAvatar;
            }
            
            NSTimeInterval timestamp = [NSDate date].timeIntervalSince1970;
            NSNumber *key = @(floor(timestamp));
            
            if (![userNotifications.filterPool objectForKey:key]) {
                notificationModel.filterKey = key;
                [userNotifications.filterPool setObject:notificationModel forKey:key];
                [userNotifications.notificationsQueue addObject:notificationModel];
            }
            
            [userNotifications executeTask];
        });
    });
    
}

- (void)executeTask {
    if (self.executing) return;
    HJNotificationModel *notificationModel = self.notificationsQueue.firstObject;
    if (notificationModel) {
        [self pushNotificationsWithModel:notificationModel];
    } else {
        NSLog(@"任务执行完成");
    }
}

- (HJNotificationView *)notificationsView {
    if (!_notificationsView) {
        _notificationsView = [[HJNotificationView alloc] init];
        UIPanGestureRecognizer *panGestureRecognizer = [[UIPanGestureRecognizer alloc] initWithTarget:self action:@selector(panGestureRecognized:)];
        [_notificationsView addGestureRecognizer:panGestureRecognizer];
        [_notificationsView addTapGesturesWithTarget:self action:@selector(tapNotificationsView)];
        _panGestureRecognizer = panGestureRecognizer;
    }
    return _notificationsView;
}

- (void)tapNotificationsView {
    if (self.notificationsView.delayedBlock) {
        dispatch_block_cancel(self.notificationsView.delayedBlock);
        self.notificationsView.delayedBlock = nil;
    }
    [self dismiss];
    
    HJChatSessionModel *sessionModel = [HJChatSessionModel sessionModelWithSessionId:self.notificationsView.model.sessionId sessionUserd:self.notificationsView.model.sendUserId chatType:self.notificationsView.model.chatType sessionName:self.notificationsView.model.title];
    [HJChatController showWithSessionModel:sessionModel];
}

- (void)pushNotificationsWithModel:(HJNotificationModel *)model {
    
    UIWindow *mainWidow = getMainWindow();
    
    if (!self.userSettingModel.noticePreview) {
        model.body = @"Sent you a message";
    }
    
    self.notificationsView.model = model;
    [mainWidow addSubview:self.notificationsView];
    self.notificationsView.frame = CGRectMake(10, -self.notificationsView.contentSize.height - 20, self.notificationsView.contentSize.width, self.notificationsView.contentSize.height);

    
    self.executing = YES;
    
    AVAudioSession *audioSession = [AVAudioSession sharedInstance];
    BOOL isMuted = audioSession.outputVolume == 0;
    NSLog(@"isMuted = %d", isMuted);
        if (!isMuted) {
            if (self.userSettingModel.noticeSound) {
                [self playSystemSound];
            }
        }
    
    if (self.userSettingModel.noticeVibration) {
        AudioServicesPlaySystemSound(kSystemSoundID_Vibrate);
    }
    
    [UIView animateWithDuration:0.5 delay:0 usingSpringWithDamping:0.85 initialSpringVelocity:0.8 options:UIViewAnimationOptionCurveEaseIn animations:^{
        self.notificationsView.tj_y = KStatusBarHight;
    } completion:^(BOOL finished) {
    }];
    
    TJWeakify(self);
    self.notificationsView.delayedBlock = dispatch_block_create(DISPATCH_BLOCK_INHERIT_QOS_CLASS, ^{
        [weakself dismiss];
    });
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2.5 * NSEC_PER_SEC)), dispatch_get_main_queue(), self.notificationsView.delayedBlock);
}

- (void)dismiss {
    [UIView animateWithDuration:0.5 delay:0 usingSpringWithDamping:1 initialSpringVelocity:1 options:UIViewAnimationOptionCurveEaseOut animations:^{
        self.notificationsView.tj_y = -self.notificationsView.frame.size.height;
    } completion:^(BOOL finished) {
        self.executing = NO;
        [self.notificationsView removeFromSuperview];
        [self.notificationsQueue removeObject:self.notificationsView.model];
        [self.filterPool removeObjectForKey:self.notificationsView.model.filterKey];
        [self executeTask];
    }];
    
}

- (void)panGestureRecognized:(UIPanGestureRecognizer *)recognizer {
    if (!recognizer.isEnabled) {
        return;
    }
    
    if (recognizer.state == UIGestureRecognizerStateBegan) {
        if (self.notificationsView.delayedBlock) {
            dispatch_block_cancel(self.notificationsView.delayedBlock);
            self.notificationsView.delayedBlock = nil;
        }
        [self dismiss];
        return;
    }
}

- (void)playSystemSound {
    NSString *soundIDName = @"messageSound.mp3";
    NSString *urlString = [NSString stringWithFormat:@"%@",[[NSBundle mainBundle] pathForResource:soundIDName ofType:nil]];
    NSURL *url = [NSURL URLWithString:urlString];
    static SystemSoundID soundID = 10000;
    AudioServicesCreateSystemSoundID((__bridge CFURLRef _Nonnull)url, &soundID);
    AudioServicesPlaySystemSound(soundID);
}


- (void)pushNotificationsWithTitle:(nullable NSString *)title subtitle:(nullable NSString *)subtitle body:(nullable NSString *)body avatarImage:(nullable UIImage *)avatarImage appLogo:(nullable UIImage *)appLogo {
    
}


+ (void)requestAuthorizationWithOptionsCompletionHandler:(void (^)(BOOL granted, NSError *__nullable error))completionHandler {
//    UNUserNotificationCenter *center = [UNUserNotificationCenter currentNotificationCenter];
//    [center requestAuthorizationWithOptions:(UNAuthorizationOptionAlert | UNAuthorizationOptionBadge | UNAuthorizationOptionSound)
//                          completionHandler:completionHandler];
}



//- (void)pushSystemNotificationsWithTitle:(nullable NSString *)title subtitle:(nullable NSString *)subtitle body:(nullable NSString *)body avatarImage:(nullable UIImage *)avatarImage {
//    
//    NSString *sendUserId = _sendUserId ?: @"";
//    
//    INImage *personAvatarImage = [INImage imageWithImageData:UIImagePNGRepresentation(avatarImage)];;
//    if (avatarImage) {
//        personAvatarImage = [INImage imageWithImageData:UIImagePNGRepresentation(avatarImage)];
//    }
//    
//    UNUserNotificationCenter *center = [UNUserNotificationCenter currentNotificationCenter];
//    center.delegate = self;
//    UNMutableNotificationContent *content = [[UNMutableNotificationContent alloc] init];
//    content.title = title;
//    content.subtitle = subtitle;
//    content.body = body;
//    //    content.sound = [UNNotificationSound defaultSound];
//    content.badge = @([UIApplication sharedApplication].applicationIconBadgeNumber + 1);
//    
//    NSString *soundName = @"messageSound.mp3";
//    content.sound = [UNNotificationSound soundNamed:soundName];
//    // 注意版本判断
//    if (@available(iOS 15.0, *)) {
//        NSPersonNameComponents *nameComponents = [[NSPersonNameComponents alloc] init];
//        nameComponents.nickname = content.title;
//        // 注意：displayName: 是显示到通信通知标题部分的文案，会顶替掉content.title，所以建议与 content.title保持一致
//        // customIdentifier 消息的id，无所谓了
//        
//        INPerson *messageSender = [[INPerson alloc] initWithPersonHandle:[[INPersonHandle alloc]initWithValue:nil type:INPersonHandleTypeUnknown] nameComponents:nameComponents displayName:content.title image:personAvatarImage contactIdentifier:sendUserId customIdentifier:sendUserId isMe:NO suggestionType:(INPersonSuggestionTypeNone)];
//        
//        // initWithSpokenPhrase 展示的是subtitle部分，所以与content.subtitle保持一致，不写的话content.subtitle是显示不出来的
//        INSendMessageIntent *intent = [[INSendMessageIntent alloc] initWithRecipients:@[messageSender] outgoingMessageType:(INOutgoingMessageTypeOutgoingMessageText) content:content.body speakableGroupName:[[INSpeakableString alloc]initWithSpokenPhrase:content.subtitle ?: @""] conversationIdentifier:_sessionId serviceName:nil sender:messageSender attachments:nil];
//        [intent setImage:personAvatarImage forParameterNamed:@"speakableGroupName"];
//        
//        INInteraction *interaction = [[INInteraction alloc] initWithIntent:intent response:nil];
//        interaction.direction = INInteractionDirectionIncoming;
//        [interaction donateInteractionWithCompletion:nil];
//        
//        // requestWithIdentifier 通知的id  可以与 上面 customIdentifier保持一致
//        // 关键代码 就是 contentByUpdatingWithProvider:intent 这个创建方法。
//        
//        UNNotificationRequest *request = [UNNotificationRequest requestWithIdentifier: _msgId content:[content contentByUpdatingWithProvider:intent error:nil] trigger:nil];
//        [center addNotificationRequest:request withCompletionHandler:^(NSError *_Nullable error) {
//            NSLog(@"成功添加推送");
//        }];
//    } else {
//        UNNotificationRequest *request = [UNNotificationRequest requestWithIdentifier:_msgId content:content trigger:nil];
//        [center addNotificationRequest:request withCompletionHandler:^(NSError *_Nullable error) {
//            NSLog(@"成功添加推送");
//        }];
//    }
//}


//
//- (void)userNotificationCenter:(UNUserNotificationCenter *)center willPresentNotification:(UNNotification *)notification withCompletionHandler:(void (^)(UNNotificationPresentationOptions options))completionHandler {
//    
//    if (@available(iOS 15.0, *)) {
//        completionHandler(UNNotificationPresentationOptionList | UNNotificationPresentationOptionBanner | UNNotificationPresentationOptionSound | UNNotificationPresentationOptionBadge);
//    } else {
//        completionHandler(UNNotificationPresentationOptionAlert | UNNotificationPresentationOptionSound | UNNotificationPresentationOptionBadge);
//    }
//}
//
//
//- (void)userNotificationCenter:(UNUserNotificationCenter *)center didReceiveNotificationResponse:(UNNotificationResponse *)response withCompletionHandler:(void (^)(void))completionHandler {
//    
//    NSLog(@"userNotificationCenter");
//    UNNotificationContent *content = response.notification.request.content;
//    
//    NSString *title = content.title;
//    NSString *body = content.body;
//    UNNotificationSound *sound = content.sound;
//    
//    NSLog(@"Received notification with title: %@, body: %@, sound: %@", title, body, sound);
//    // 处理用户点击通知的操作
//    if ([response.actionIdentifier isEqualToString:UNNotificationDefaultActionIdentifier]) {
//        NSLog(@"User tapped on the notification");
//        // 在这里执行你想要的操作
//    }
//    
//    // 完成回调
//    completionHandler();
//}

@end
